import CURDHelper from '@/utils/CURDHelper'
import PageConfig from '@/utils/pageConfig'
import { getBtnCtr } from '@/utils/BtnControl'
import Query from '@/components/Query';
import { isNumber } from '@/utils/validate';
import { VxeUI } from 'vxe-pc-ui';
import XEUtils from 'xe-utils';
import XLSX from 'xlsx';
export default {
  name: 'BaseSupplier',
  components: {
    Query
  },
  data() {
    const sfmrItemRender = {
      name: 'VxeSelect',
      options: [
        { label: '否', value: 'N' },
        { label: '是', value: 'Y' }
      ],
    }
    return {
      sfmrItemRender,
      componentSize: PageConfig.ComponentSize,
      duration: PageConfig.Duration,
      btnPromission: '',
      editModal: false,
      editAccountModal: false,
      BaseApiUrl: '/api/Xmjcqdxx',
      BaseApiUrl2: '/api/Xmjcqdxxyhzh',
      importModal: false,
      QueryConditions: [],
      QueryConfig: [{
        title: '渠道名称',
        field: 'khmc',
        type: 'input',
        value: '',
        placeholder: '请输入渠道名称以查询',
      }
      ],
      GridOptions: {
        id: 'BaseSupplier_MainGrid',
        border: true,
        stripe: true,
        loading: false,
        size: PageConfig.ComponentSize,
        height: 700,
        columnConfig: {
          resizable: true
        },
        rowConfig: {
          isHover: true,
          isCurrent: true
        },
        checkboxConfig: {
          highlight: true,
          range: true
        },
        exportConfig: {
        },
        toolbarConfig: {
          custom: true,
          export: true,
          slots: {
            buttons: 'customButtons'
          }
        },
        customConfig: {
          mode: 'drawer',
          storage: true
        },
        columns: [
          { type: 'seq', width: 50 },
          { type: 'checkbox', width: 35 },
          { field: 'qdbm', title: '渠道编码', sortable: true, minWidth: 100, showOverflow: true },
          { field: 'qdmc', title: '渠道名称', sortable: true, minWidth: 150, showOverflow: true },
          { field: 'qdjc', title: '渠道简称', sortable: true, minWidth: 100, showOverflow: true },
          {
            field: 'kyrq', title: '开业日期', sortable: true, minWidth: 120, showOverflow: true,
            formatter({ cellValue }) {
              return XEUtils.toDateString(cellValue, 'yyyy-MM-dd');
            }
          },
          { field: 'zczj', title: '注册资金', minWidth: 80 },
          { field: 'ygrs', title: '员工人数', minWidth: 80 },
          { field: 'lxr', title: '联系人', minWidth: 80 },
          { field: 'lxdh', title: '联系电话', minWidth: 80 },
          { field: 'gsdz', title: '公司地址', minWidth: 100, showOverflow: true },
          { field: 'shdz', title: '收货地址', minWidth: 100, showOverflow: true },
          { field: 'qdly', title: '渠道来源', minWidth: 100, showOverflow: true },
          { field: 'qdzt', title: '状态', minWidth: 100, showOverflow: true, slots: { default: 'qdzt' } },
          { field: 'bz', title: '备注', minWidth: 100, showOverflow: true },
          { field: 'createtime', title: '创建时间', minWidth: 150, showOverflow: true },
          { field: 'createname', title: '创建人', minWidth: 100, showOverflow: true },
          { field: 'updatetime', title: '更新时间', minWidth: 150, showOverflow: true },
          { field: 'updatename', title: '更新人', minWidth: 100, showOverflow: true },
          { field: 'operation', title: '操作', fixed: 'right', width: 160, slots: { default: 'operation' } },
        ],
        data: []
      },
      PagerConfig: {
        align: 'center',
        pageSize: 25,
        total: 0,
        currentPage: 1,
        pageSizes: [10, 25, 50, 100, 200],
      },
      FormOptions: {
        'title-width': 140,
        border: true,
        titleBackground: true,
        data: {
          id: -1,
          createid: '',
          createtime: '',
          createname: '',
          updateid: '',
          updatetime: '',
          updatename: '',
          qdbm: '',
          qdmc: '',
          qdjc: '',
          kyrq: '',
          zczj: '',
          ygrs: '',
          lxr: '',
          lxdh: '',
          gsdz: '',
          shdz: '',
          khly: '',
          qdzt: 'Y',
          bz: '',
        },
        rules: {
          qdbm: [{ required: true, message: '请输入渠道编码', trigger: 'blur' }],
          qdmc: [{ required: true, message: '请输入渠道名称', trigger: 'blur' }],
          zczj: [{ validator: this.ValidatorNumber }],
        },
        items: [
          { field: 'qdbm', title: '渠道编码', span: 12, itemRender: { name: 'VxeInput', props: { placeholder: '请输入客户编码' } } },
          { field: 'qdmc', title: '渠道名称', span: 12, itemRender: { name: 'VxeInput', props: { placeholder: '请输入客户名称' } } },
          { field: 'qdjc', title: '客户简称', span: 12, itemRender: { name: 'VxeInput', props: { placeholder: '请输入客户简称' } } },
          { field: 'kyrq', title: '开业日期', span: 12, itemRender: { name: 'VxeDatePicker', type: 'date' } },
          { field: 'zczj', title: '注册资金', span: 12, itemRender: { name: 'VxeInput', props: { placeholder: '请输入注册资金' } } },
          { field: 'ygrs', title: '员工人数', span: 12, itemRender: { name: 'VxeInput', props: { placeholder: '请输入员工人数' } } },
          { field: 'lxr', title: '联系人', span: 12, itemRender: { name: 'VxeInput', props: { placeholder: '请输入联系人' } } },
          { field: 'lxdh', title: '联系电话', span: 12, itemRender: { name: 'VxeInput', props: { placeholder: '请输入联系电话' } } },
          { field: 'gsdz', title: '公司地址', span: 24, itemRender: { name: 'VxeInput', props: { placeholder: '请输入公司地址' } } },
          { field: 'shdz', title: '收货地址', span: 24, itemRender: { name: 'VxeInput', props: { placeholder: '请输入收货地址' } } },
          { field: 'khly', title: '渠道来源', span: 12, itemRender: { name: 'VxeInput', props: { placeholder: '请输入渠道来源' } } },
          {
            field: 'qdzt', title: '状态', span: 12, resetValue: 'Y',
            itemRender: { name: 'VxeSelect', options: [{ value: 'Y', label: '有效' }, { value: 'N', label: '失效' }], defaultValue: 'Y' }
          },
          { field: 'bz', title: '备注', span: 24, itemRender: { name: 'VxeTextarea', maxlegnth: 500, clearable: true, showWordCount: true }, placeholder: '请输入备注' },
          {
            align: 'center',
            span: 24,
            itemRender: {
              name: 'VxeButtonGroup',
              options: [{
                type: 'submit', content: '提交', status: 'primary'
              }, {
                type: 'reset', content: '重置'
              }]
            }
          }
        ]
      },
      ImportGridOptions: {
        id: 'BaseSupplier_ImportGrid',
        border: true,
        stripe: true,
        loading: false,
        size: PageConfig.ComponentSize,
        height: 350,
        columnConfig: {
          resizable: true
        },
        rowConfig: {
          isHover: true,
          isCurrent: true
        },
        checkboxConfig: {
          highlight: true,
          range: true
        },
        columns: [
          { type: 'seq', width: 50 },
          { type: 'checkbox', width: 35 },
          { field: 'qdbm', title: '渠道编码', sortable: true, minWidth: 120, showOverflow: true },
          { field: 'qdmc', title: '渠道名称', sortable: true, minWidth: 120, showOverflow: true },
          { field: 'qdjc', title: '渠道简称', minWidth: 100, showOverflow: true },
          { field: 'kyrq', title: '开业日期', minWidth: 120, showOverflow: true },
          { field: 'zczj', title: '注册资金', minWidth: 100, showOverflow: true },
          { field: 'ygrs', title: '员工人数', minWidth: 120, showOverflow: true },
          { field: 'lxr', title: '联系人', minWidth: 100, showOverflow: true },
          { field: 'lxdh', title: '联系电话', minWidth: 100, showOverflow: true },
          { field: 'gsdz', title: '公司地址', minWidth: 100, showOverflow: true },
          { field: 'shdz', title: '收货地址', minWidth: 100, showOverflow: true },
          { field: 'khly', title: '渠道来源', minWidth: 100, showOverflow: true },
          { field: 'bz', title: '备注', minWidth: 80, showOverflow: true },
        ],
        data: []
      },
      AccountGridOptions: {
        id: 'BaseSupplierAccountGrid',
        border: true,
        stripe: true,
        loading: false,
        size: PageConfig.ComponentSize,
        height: 530,
        columnConfig: {
          resizable: true
        },
        rowConfig: {
          isHover: true,
          isCurrent: true
        },
        editConfig: {
          trigger: 'click',
          mode: 'row',
          showStatus: true
        },
        exportConfig: {
        },
        toolbarConfig: {
          tools: [
            { code: 'childAdd', icon: 'vxe-icon-add', circle: true }
          ]
        },
        customConfig: {
          mode: 'drawer',
          storage: true
        },
        columns: [
          { type: 'seq', width: 50 },
          { field: 'yhmc', title: '银行名称', minWidth: 200, showOverflow: true, editRender: { name: 'VxeInput' } },
          { field: 'yhzh', title: '银行账号', minWidth: 200, showOverflow: true, editRender: { name: 'VxeInput' } },
          { field: 'hm', title: '户名', minWidth: 100, showOverflow: true, editRender: { name: 'VxeInput' } },
          { field: 'sfmr', title: '默认账号', minWidth: 90, showOverflow: true, slots: { default: 'accountStatus' }, editRender: sfmrItemRender },
          { field: 'operation', title: '操作', fixed: 'right', width: 120, slots: { default: 'operation' } },
        ],
        data: []
      },
      EditRow: undefined,
    }
  },
  created() {
    // 动态头部按钮
    this.btnPromission = getBtnCtr(
      this.$route.path,
      this.$store.getters.userPermission
    )
  },
  methods: {
    ValidatorNumber(e) {
      if (!e.itemValue) {
        return;
      }
      if (!isNumber(e.itemValue)) {
        return new Error('请输入数字');
      } else {
        if (e.itemValue < 0) {
          return new Error('请输入大于等于0的数字');
        }
      }
    },
    handleQuery(e) {
      this.QueryConditions = e;
      this.DoQuery(e);
    },
    handlePageChange() {
      this.DoQuery(this.QueryConditions);
    },
    handleBatchDelete() {
      let rows = this.$refs.maingrid.getCheckboxRecords(true);
      this.DoBatchDelete(rows);
    },
    handleAdd() {
      this.FormOptions.data = {
        id: -1,
        createid: '',
        createtime: '',
        createname: '',
        updateid: '',
        updatetime: '',
        updatename: '',
        qdbm: '',
        qdmc: '',
        qdjc: '',
        kyrq: '',
        zczj: '',
        ygrs: '',
        lxr: '',
        lxdh: '',
        gsdz: '',
        shdz: '',
        khly: '',
        qdzt: 'Y',
        bz: '',
      }
      this.editModal = true;
    },
    handleEdit(row) {
      this.FormOptions.data = row;
      this.editModal = true;
    },
    handleDelete(row) {
      this.DoDelete(row);
    },
    handleEditModalSubmit() {
      this.FormOptions.data.id == -1 ? this.DoAdd() : this.DoEdit();
    },
    handleEditModalReset() {

    },
    handleImport() {
      this.DoImport();
    },
    handleImprotConfirm() {
      this.DoImportConfirm();
    },
    DoQuery(e) {
      let request = {
        isPaging: true,
        pageSize: this.PagerConfig.pageSize,
        pageIndex: this.PagerConfig.currentPage,
        queryConditions: e,
        orderByConditions: []
      }
      CURDHelper.Query(request, this.BaseApiUrl)
        .then(res => {
          this.GridOptions.data = res.data;
          this.PagerConfig.total = res.totalNumber;
        }).catch(err => {
          VxeUI.modal.message({
            content: err,
            status: 'error',
            duration: this.duration
          })
        })
    },
    DoAdd() {
      //新增
      CURDHelper.Add(this.FormOptions.data, null, this.BaseApiUrl)
        .then(res => {
          VxeUI.modal.message({
            content: '新增数据成功',
            status: 'success',
            duration: this.duration
          })
          this.FormOptions.data.id = -1;
          this.editModal = false;
        }).catch(err => {
          VxeUI.modal.message({
            content: err,
            status: 'error',
            duration: this.duration
          })
        })
    },
    DoEdit() {
      //编辑
      CURDHelper.EditWithConfirm('是否修改当前数据', this.FormOptions.data, null, this.BaseApiUrl)
        .then(res => {
          VxeUI.modal.message({
            content: '编辑数据成功',
            status: 'success',
            duration: this.duration
          });
          this.FormOptions.data.id = -1;
          this.editModal = false;
        }).catch(err => {
          VxeUI.modal.message({
            content: err,
            status: 'error',
            duration: this.duration
          })
        })
    },
    DoDelete(row) {
      //删除
      let deleteModel = {
        ID: row.id,
        DeleteRemark: ''
      };
      CURDHelper.DeleteWithConfirm('是否删除当前数据', deleteModel, null, this.BaseApiUrl)
        .then(res => {
          VxeUI.modal.message({
            content: '删除数据成功',
            status: 'success',
            duration: this.duration
          })
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({
            content: err,
            status: 'error',
            duration: this.duration
          })
        })
    },
    DoBatchDelete(rows) {
      //删除
      let deleteList = [];
      rows.forEach(row => {
        deleteList.push({
          ID: row.id,
          DeleteRemark: ''
        })
      })
      CURDHelper.DeleteWithConfirm('是否删除当前已选择数据，删除后不能恢复', null, deleteList, this.BaseApiUrl)
        .then(res => {
          VxeUI.modal.message({
            content: '删除数据成功',
            status: 'success',
            duration: this.duration
          })
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({
            content: err,
            status: 'error',
            duration: this.duration
          })
        })
    },
    DoImport() {
      VxeUI.readFile().then((e) => {
        const reader = new FileReader()
        this.ImportGridOptions.data = [];
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const resultJosn = XLSX.utils.sheet_to_json(worksheet);

          resultJosn.forEach(item => {
            if (!item['渠道编码'] || !item['渠道名称']) {
              return;
            }
            var date = new Date('1900-01-01');
            var currKyrq = date.setDate(item['开业日期']);
            let newRow = {
              qdbm: item['渠道编码'],
              qdmc: item['渠道名称'],
              qdjc: item['渠道简称'],
              kyrq: XEUtils.toDateString(currKyrq),
              zczj: item['注册资金'],
              ygrs: item['员工人数'],
              lxr: item['联系人'],
              lxdh: item['联系电话'],
              gsdz: item['公司地址'],
              shdz: item['收货地址'],
              khly: item['客户来源'],
              qdzt: 'Y',
              bz: item['备注']
            }
            this.ImportGridOptions.data.push(newRow);
          })
          this.importModal = true;
        }
        reader.readAsArrayBuffer(e.file);
      })
    },
    DoImportConfirm() {
      let postList = this.$refs.importModalGrid.getCheckboxRecords(true);
      if (!postList || postList.length < 1) {
        postList = this.ImportGridOptions.data;
      }
      CURDHelper.Add(null, postList, this.BaseApiUrl)
        .then(res => {
          VxeUI.modal.message({ content: '导入数据成功', status: 'success', duration: this.duration });
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    handleAccountToolClick({ code }) {
      if (code == 'childAdd') {
        this.AccountGridOptions.data.push({
          id: 0,
          yhmc: undefined,
          yhzh: undefined,
          hm: undefined,
          sfmr: 'N'
        })
      }
    },
    handleAccountEdit(row) {
      this.EditRow = row;
      let queryConditions = [{
        column: 'qdid',
        content: this.EditRow.id,
        condition: '0'
      }]
      this.DoAccountQuery(queryConditions);
      this.editAccountModal = true;
    },
    hasAccountEditStatus(row) {
      return this.$refs.accountGrid.isEditByRow(row);
    },
    handleAccountSave(row) {
      this.$refs.accountGrid.clearEdit();
      if (!row.yhmc || row.yhmc.length < 1) {
        VxeUI.modal.message({ content: '请填写银行名称', status: 'error', duration: this.duration });
        return;
      }
      if (!row.yhzh && row.yhzh.length < 1) {
        VxeUI.modal.message({ content: '请填写银行账号', status: 'error', duration: this.duration });
        return;
      }
      if (!row.hm && row.hm.length < 1) {
        VxeUI.modal.message({ content: '请填写户名', status: 'error', duration: this.duration });
        return;
      }
      row.qdid = this.EditRow.id;
      row.id == 0 ? this.DoAccountAdd(row) : this.DoAccountEdit(row);
    },
    DoAccountAdd(row) {
      this.$refs.accountGrid.clearEdit();
      CURDHelper.Add(row, null, `${this.BaseApiUrl2}`)
        .then(res => {
          VxeUI.modal.message({ content: '新增数据成功', status: 'success', duration: this.duration });
          let queryConditions = [{
            column: 'qdid',
            content: this.EditRow.id,
            condition: '0'
          }]
          this.DoAccountQuery(queryConditions);
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    DoAccountEdit(row) {
      this.$refs.accountGrid.clearEdit();
      CURDHelper.Edit(row, null, `${this.BaseApiUrl2}`)
        .then(res => {
          VxeUI.modal.message({ content: '编辑数据成功', status: 'success', duration: this.duration })
          let queryConditions = [{
            column: 'qdid',
            content: this.EditRow.id,
            condition: '0'
          }]
          this.DoAccountQuery(queryConditions);
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    DoAccountQuery(e) {
      let queryConditions = e || [];
      let request = {
        isPaging: false,
        pageSize: 1,
        pageIndex: 1,
        queryConditions: queryConditions,
        orderByConditions: [{
          column: 'createtime',
          condition: 'asc'
        }]
      }
      CURDHelper.Query(request, this.BaseApiUrl2)
        .then(res => {
          this.AccountGridOptions.data = res.data;
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    handleAccountCancel() {
      this.$refs.accountGrid.clearEdit();
    },
    handleAccountDelete(row) {
      this.DoAccountDelete(row);
    },
    DoAccountDelete(row) {
      //删除
      let deleteModel = {
        ID: row.id,
        DeleteRemark: ''
      };
      CURDHelper.DeleteWithConfirm('是否删除当前数据', deleteModel, null, this.BaseApiUrl2)
        .then(res => {
          VxeUI.modal.message({ content: '删除数据成功', status: 'success', duration: this.duration })
          let queryConditions = [{
            column: 'qdid',
            content: this.EditRow.id,
            condition: '0'
          }]
          this.DoAccountQuery(queryConditions);
        }).catch(err => {
          VxeUI.modal.message({ content: err, status: 'error', duration: this.duration })
        })
    },
    handleAccountGridEdit(row) {
      this.$refs.accountGrid.setEditRow(row);
    },
  }

}
